import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'daily_events_logic.dart';
import '../status_logic.dart';

/// 今日事件详情页面
class DailyEventsView extends GetView<DailyEventsLogic> {
  const DailyEventsView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF282528),
      appBar: AppBar(
        title: const Text(
          '今日事件',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        elevation: 0,
        backgroundColor: const Color(0xFF282528),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Get.back(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.calendar_today, color: Colors.white),
            onPressed: () {
              // 切换日期
            },
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            // 日期显示
            Container(
              width: double.infinity,
              padding: EdgeInsets.all(20.w),
              child: Text(
                controller.getCurrentDate(),
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w500,
                  color: Colors.white,
                ),
                textAlign: TextAlign.center,
              ),
            ),
            Expanded(
              child: Obx(() {
                if (controller.state.isLoading.value) {
                  return const Center(
                    child: CircularProgressIndicator(
                      color: Colors.orange,
                    ),
                  );
                }

                return SingleChildScrollView(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 20.w),
                    child: Column(
                      children: [
                        // 日常打卡部分
                        _buildDailyCheckInSection(),
                        SizedBox(height: 20.h),
                        // 娱乐活动部分
                        _buildEntertainmentSection(),
                        SizedBox(height: 20.h),
                        // 症状部分
                        _buildSymptomsSection(),
                        SizedBox(height: 20.h),
                        // 自定义事件部分
                        _buildCustomEventSection(),
                        SizedBox(height: 100.h), // 为底部按钮留出空间
                      ],
                    ),
                  ),
                );
              }),
            ),
          ],
        ),
      ),
      // 底部AI评分按钮
      bottomNavigationBar: Container(
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          color: const Color(0xFF2A2A2A),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.3),
              spreadRadius: 1,
              blurRadius: 8,
              offset: const Offset(0, -2),
            ),
          ],
        ),
        child: SafeArea(
          child: ElevatedButton(
            onPressed: _showAiScoreDialog,
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xffe2582e),
              foregroundColor: Colors.white,
              padding: EdgeInsets.symmetric(vertical: 16.h),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(25.r),
              ),
            ),
            child: Text(
              'AI评分',
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建日常打卡部分
  Widget _buildDailyCheckInSection() {
    return _buildSection(
      title: '当前健康计划推荐打卡事项',
      child: Obx(() {
        final allTags = controller.state.dailyCheckInEvents.toList();
        final tags = allTags.take(3).toList(); // 取前3个标签
        tags.add('显示更多');
        return _buildQuestionSection(
          question: '',
          tags: tags,
          sectionType: 'health',
        );
      }),
    );
  }

  /// 构建娱乐活动部分
  Widget _buildEntertainmentSection() {
    return _buildSection(
      title: '你今天有什么娱乐活动？',
      child: Obx(() {
        final allTags = controller.state.entertainmentEvents.toList();
        final tags = allTags.take(3).toList(); // 取前3个标签
        tags.add('显示更多');
        return _buildQuestionSection(
          question: '',
          tags: tags,
          sectionType: 'entertainment',
        );
      }),
    );
  }

  /// 构建症状部分
  Widget _buildSymptomsSection() {
    return _buildSection(
      title: '你今天有什么症状？',
      child: Obx(() {
        final allTags = controller.state.symptomsEvents.toList();
        final tags = allTags.take(3).toList(); // 取前3个标签
        tags.add('显示更多');
        return _buildQuestionSection(
          question: '',
          tags: tags,
          sectionType: 'symptoms',
        );
      }),
    );
  }

  /// 构建自定义事件部分
  Widget _buildCustomEventSection() {
    return _buildSection(
      title: '',
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Obx(() {
            final hasSelectedTags = controller.selectedTags.isNotEmpty;
            return Text(
              hasSelectedTags ? '自定义  可继续补充内容...' : '自定义  今天发生了什么？在这里添加任何内容...',
              style: TextStyle(
                fontSize: 14.sp,
                color: hasSelectedTags ? Colors.orange[300] : Colors.grey[400],
              ),
            );
          }),
          SizedBox(height: 12.h),
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: const Color(0xFF3A3A3A),
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: TextField(
              controller: controller.customEventController,
              decoration: InputDecoration(
                hintText: '选择上方标签会自动填入，或直接输入自定义内容...',
                hintStyle: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[500],
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.zero,
              ),
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.white,
              ),
              maxLines: 5,
              minLines: 3,
              textInputAction: TextInputAction.done,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建章节容器
  Widget _buildSection({required String title, required Widget child}) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: const Color(0xFF2A2A2A),
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.3),
            spreadRadius: 1,
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (title.isNotEmpty) ...[
            Text(
              title,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            SizedBox(height: 16.h),
          ],
          child,
        ],
      ),
    );
  }

  /// 构建问题和标签部分
  Widget _buildQuestionSection(
      {required String question,
      required List<String> tags,
      String? sectionType}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (question.isNotEmpty) ...[
          Text(
            question,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 12.h),
        ],
        Wrap(
          spacing: 8.w,
          runSpacing: 8.h,
          children: tags
              .map((tag) => _buildTag(tag, sectionType: sectionType))
              .toList(),
        ),
      ],
    );
  }

  /// 构建标签
  Widget _buildTag(String text, {String? sectionType}) {
    return GestureDetector(
      onTap: () {
        // 处理标签点击
        if (text == '显示更多') {
          _showMoreOptionsBottomSheet(sectionType: sectionType);
        } else {
          controller.toggleTag(text);
        }
      },
      child: Obx(() {
        final isSelected = controller.selectedTags.contains(text);
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: isSelected ? Colors.orange[800] : const Color(0xFF3A3A3A),
            borderRadius: BorderRadius.circular(20.r),
            border: isSelected
                ? Border.all(color: Colors.orange, width: 1)
                : Border.all(color: Colors.grey[600]!, width: 1),
          ),
          child: Text(
            text,
            style: TextStyle(
              fontSize: 12.sp,
              color: isSelected ? Colors.white : Colors.grey[300],
              fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
            ),
          ),
        );
      }),
    );
  }

  /// 显示AI评分弹窗
  void _showAiScoreDialog() async {
    // 验证：如果没有选择任何标签，自定义内容必须填写
    if (controller.selectedTags.isEmpty &&
        controller.customEventController.text.trim().isEmpty) {
      Toast.show('请选择标签或填写自定义内容');
      return;
    }

    // 显示加载状态
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Container(
          padding: EdgeInsets.all(24.w),
          decoration: BoxDecoration(
            color: const Color(0xFF2A2A2A),
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(
                color: Colors.orange,
              ),
              SizedBox(height: 16.h),
              Text(
                'AI正在分析您的数据...',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: false,
    );

    try {
      final aiData = await controller.requestAiScore();

      // 关闭加载弹窗
      Get.back();

      // 显示AI评分结果
      Get.dialog(
        Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: Container(
            padding: EdgeInsets.all(24.w),
            decoration: BoxDecoration(
              color: const Color(0xFF2A2A2A),
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  'AI打分',
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                SizedBox(height: 24.h),
                // 分数显示
                Container(
                  width: 120.w,
                  height: 120.w,
                  decoration: BoxDecoration(
                    color: const Color(0xFF3A3A3A),
                    shape: BoxShape.circle,
                  ),
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '${aiData['score']}',
                          style: TextStyle(
                            fontSize: 48.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                        Container(
                          width: 40.w,
                          height: 2.h,
                          color: Colors.white,
                        ),
                        SizedBox(height: 4.h),
                        Text(
                          '分',
                          style: TextStyle(
                            fontSize: 16.sp,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                SizedBox(height: 20.h),
                // 事件和AI评价
                Container(
                  padding: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    color: const Color(0xFF3A3A3A),
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 自定义事件
                      if (aiData['event'] != null &&
                          aiData['event'].toString().isNotEmpty) ...[
                        Text(
                          '自定义事件：',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        SizedBox(height: 4.h),
                        Text(
                          '"${aiData['event']}"',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        SizedBox(height: 12.h),
                      ],
                      // AI评语
                      Text(
                        'AI评语：',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.white,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      SizedBox(height: 4.h),
                      Text(
                        '"${aiData['aiComment']}"',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.grey[400],
                          height: 1.4,
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 24.h),
                // 按钮组
                Row(
                  children: [
                    // 不记录按钮
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () => Get.back(),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.grey[300],
                          foregroundColor: Colors.grey[700],
                          padding: EdgeInsets.symmetric(vertical: 14.h),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(25.r),
                          ),
                        ),
                        child: Text(
                          '不记录',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 12.w),
                    // 记录按钮
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () async {
                          // 显示加载状态
                          Get.dialog(
                            Dialog(
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(20.r),
                              ),
                              child: Container(
                                padding: EdgeInsets.all(24.w),
                                decoration: BoxDecoration(
                                  color: const Color(0xFF2A2A2A),
                                  borderRadius: BorderRadius.circular(20.r),
                                ),
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    CircularProgressIndicator(
                                      color: Colors.orange,
                                    ),
                                    SizedBox(height: 16.h),
                                    Text(
                                      '正在记录...',
                                      style: TextStyle(
                                        fontSize: 16.sp,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            barrierDismissible: false,
                          );

                          try {
                            // 调用记录接口
                            final success =
                                await controller.recordAiScore(aiData);
                            // 关闭加载弹窗
                            Get.back();
                            if (success) {
                              // 关闭AI评分弹窗
                              Get.back();
                              // 返回首页
                              Get.back();
                              // 刷新首页事件小计列表
                              try {
                                final statusLogic = Get.find<StatusLogic>();
                                await statusLogic.refreshDailyEventsSummary();
                              } catch (e) {
                                print('刷新事件小计失败: $e');
                              }
                            }
                          } catch (e) {
                            // 关闭加载弹窗
                            Get.back();
                            Toast.show('记录失败，请重试');
                          }
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.grey[800],
                          foregroundColor: Colors.white,
                          padding: EdgeInsets.symmetric(vertical: 14.h),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(25.r),
                          ),
                        ),
                        child: Text(
                          '记录',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        barrierDismissible: true,
      );
    } catch (e) {
      // 关闭加载弹窗
      Get.back();
      // 显示错误提示
      Toast.show('AI评分失败，请重试');
    }
  }

  /// 显示更多选项底部弹窗
  void _showMoreOptionsBottomSheet({String? sectionType}) {
    // 根据sectionType确定标题和内容
    String title;

    switch (sectionType) {
      case 'health':
        title = '健康计划推荐打卡事项';
        break;
      case 'entertainment':
        title = '娱乐活动选择';
        break;
      case 'symptoms':
        title = '症状选择';
        break;
      default:
        title = '选择活动';
    }

    Get.bottomSheet(
      Container(
        height: Get.height * 0.8, // 弹窗高度为屏幕的80%
        decoration: BoxDecoration(
          color: const Color(0xFF2A2A2A),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.r),
            topRight: Radius.circular(20.r),
          ),
        ),
        child: Column(
          children: [
            // 顶部拖拽指示器
            Container(
              margin: EdgeInsets.only(top: 12.h),
              width: 40.w,
              height: 4.h,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(2.r),
              ),
            ),
            // 标题
            Padding(
              padding: EdgeInsets.all(20.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                  IconButton(
                    onPressed: () => Get.back(),
                    icon: Icon(
                      Icons.close,
                      size: 24.sp,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
            // 活动选项列表
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Obx(() {
                  List<String> activities;
                  switch (sectionType) {
                    case 'health':
                      activities = controller.state.dailyCheckInEvents.toList();
                      break;
                    case 'entertainment':
                      activities =
                          controller.state.entertainmentEvents.toList();
                      break;
                    case 'symptoms':
                      activities = controller.state.symptomsEvents.toList();
                      break;
                    default:
                      activities = ['电影', '观看比赛', '音乐', '派对', '旅行', '电子游戏'];
                  }

                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 活动标签网格
                      Wrap(
                        spacing: 8.w,
                        runSpacing: 8.h,
                        children: [
                          ...activities
                              .map((activity) => _buildActivityTag(activity,
                                  sectionType: sectionType))
                              .toList(),
                          // 添加加号按钮
                          _buildAddButton(sectionType: sectionType),
                        ],
                      ),
                      SizedBox(height: 20.h),
                    ],
                  );
                }),
              ),
            ),
            // 底部确认按钮
            Container(
              padding: EdgeInsets.all(20.w),
              decoration: BoxDecoration(
                color: const Color(0xFF2A2A2A),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.3),
                    spreadRadius: 1,
                    blurRadius: 8,
                    offset: const Offset(0, -2),
                  ),
                ],
              ),
              child: SafeArea(
                child: SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () {
                      // 处理确认选择
                      Get.back();
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.orange,
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(vertical: 16.h),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(25.r),
                      ),
                    ),
                    child: Text(
                      sectionType == 'health'
                          ? '添加到健康计划'
                          : sectionType == 'entertainment'
                              ? '添加到娱乐活动'
                              : sectionType == 'symptoms'
                                  ? '添加到症状'
                                  : '完成',
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }

  /// 构建活动标签
  Widget _buildActivityTag(String activity, {String? sectionType}) {
    return GestureDetector(
      onTap: () {
        // 处理活动选择
        controller.toggleTag(activity);
      },
      child: Obx(() {
        final isSelected = controller.selectedTags.contains(activity);

        // 根据sectionType确定颜色
        Color selectedColor;
        Color selectedTextColor;

        switch (sectionType) {
          case 'health':
            selectedColor = Colors.green[100]!;
            selectedTextColor = Colors.green[700]!;
            break;
          case 'entertainment':
            selectedColor = Colors.orange[100]!;
            selectedTextColor = Colors.orange[700]!;
            break;
          case 'symptoms':
            selectedColor = Colors.red[100]!;
            selectedTextColor = Colors.red[700]!;
            break;
          default:
            selectedColor = Colors.orange[100]!;
            selectedTextColor = Colors.orange[700]!;
        }

        return Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: isSelected ? selectedColor : const Color(0xFF3A3A3A),
            borderRadius: BorderRadius.circular(20.r),
            border: isSelected
                ? Border.all(color: selectedTextColor, width: 1)
                : Border.all(color: Colors.grey[600]!, width: 1),
          ),
          child: Text(
            activity,
            style: TextStyle(
              fontSize: 12.sp,
              color: isSelected ? selectedTextColor : Colors.grey[300],
              fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
            ),
          ),
        );
      }),
    );
  }

  /// 构建加号按钮
  Widget _buildAddButton({String? sectionType}) {
    return GestureDetector(
      onTap: () => _showAddCustomTagDialog(sectionType: sectionType),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
        decoration: BoxDecoration(
          color: Colors.orange[100],
          borderRadius: BorderRadius.circular(20.r),
          border: Border.all(color: Colors.orange, width: 1),
        ),
        child: Icon(
          Icons.add,
          size: 20.sp,
          color: Colors.orange[700],
        ),
      ),
    );
  }

  /// 显示添加自定义标签弹窗
  void _showAddCustomTagDialog({String? sectionType}) {
    final TextEditingController textLogic = TextEditingController();
    final RxBool isAdding = false.obs;

    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Container(
          padding: EdgeInsets.all(24.w),
          decoration: BoxDecoration(
            color: const Color(0xFF2A2A2A),
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '添加自定义标签',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 24.h),
              TextField(
                controller: textLogic,
                decoration: InputDecoration(
                  hintText: sectionType == 'health'
                      ? '输入健康项目...'
                      : sectionType == 'entertainment'
                          ? '输入娱乐活动...'
                          : sectionType == 'symptoms'
                              ? '输入症状...'
                              : '输入标签...',
                  hintStyle: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[500],
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12.r),
                    borderSide: BorderSide(color: Colors.grey[600]!),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12.r),
                    borderSide: BorderSide(color: Colors.orange),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12.r),
                    borderSide: BorderSide(color: Colors.grey[600]!),
                  ),
                  filled: true,
                  fillColor: const Color(0xFF3A3A3A),
                ),
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 24.h),
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () => Get.back(),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.grey[300],
                        foregroundColor: Colors.grey[700],
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                      ),
                      child: Text(
                        '取消',
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Obx(() => ElevatedButton(
                          onPressed: isAdding.value
                              ? null
                              : () async {
                                  final text = textLogic.text.trim();
                                  if (text.isNotEmpty) {
                                    isAdding.value = true;

                                    try {
                                      // 获取对应的tagType
                                      final tagType = controller
                                          .getTagTypeBySectionType(sectionType);

                                      // 调用API添加标签
                                      final success = await controller
                                          .addTagToServer(text, tagType);

                                      if (success) {
                                        // 添加成功，关闭弹窗
                                        Get.back();
                                        Toast.show('标签添加成功');
                                      }
                                    } finally {
                                      isAdding.value = false;
                                    }
                                  }
                                },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.orange,
                            foregroundColor: Colors.white,
                            padding: EdgeInsets.symmetric(vertical: 12.h),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12.r),
                            ),
                          ),
                          child: isAdding.value
                              ? SizedBox(
                                  width: 16.sp,
                                  height: 16.sp,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    valueColor: AlwaysStoppedAnimation<Color>(
                                        Colors.white),
                                  ),
                                )
                              : Text(
                                  '添加',
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                        )),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: true,
    );
  }
}
